<?php
class Login extends Zend_Db_Table
{
	protected $_name = 'usuario';
	protected $_primary = 'id_usuario';

    private $id_pessoaJuridica;
    private $nomeFantasia;
	private $passDecrypted;

	private function _load($user, $email){
		$db = Zend_Registry::get('db');
		$sql= 'select *
		         from usuario
		        where 1=1';
		if ($user!=null){
			$sql .= ' and ds_nome="'.$user.'"';
		}
		if ($email!=null){
			$sql .= ' and ds_mail="'.$email.'"';
		}
		$row = $db->query($sql)->fetch();
		$this->populateObject($row);
	}
	private function populateObject($values){
		$this->id_usuario	  =$values["id_usuario"];
    	$this->ds_nome	      =$values["ds_nome"];
    	$this->ds_senha       =$values["ds_senha"];
    	$this->ds_mail        =$values["ds_mail"];
    	$this->id_fisica      =$values["id_fisica"];
    	$this->id_grupo_acesso=$values["id_grupo_acesso"];
    	$this->dt_cadastro    =$values["dt_cadastro"];
    	$this->in_ativo		  =$values["in_ativo"];
	}

	public function load($id){
		$db = Zend_Registry::get('db');
		$row = $this->find($id)->current();
		$this->populateObject($row);
		/*
		$sql =
		"SELECT usu.id_usuario, usu.ds_nome, usu.id_pessoa, usu.ds_mail,
		               usu.id_grupo_acesso , psf.id_juridica,
		               psj.ds_nome as nomeFantasia
 				  FROM usuario usu
                  join pessoa pes
                    on usu.id_pessoa =  pes.id_pessoa
                  join pessoa_fisica psf
                    on usu.id_pessoa = psf.id_fisica
                  join pessoa psj
                    on psf.id_juridica = psj.id_pessoa
                 where usu.id_usuario = " .$id;
		$result = $db->query($sql)->fetch();
		$this->id_usuario = $result['id_id_usuario'];
		$this->ds_nome = $result['ds_nome'];
		$this->id_pessoa = $result['id_pessoa'];
		$this->ds_mail = $result['ds_mail'];
		$this->id_grupo_acesso = $result['id_grupo_acesso'];
		$this->id_pessoaJuridica = $result['id_juridica'];
		$this->nomeFantasia = $result['nomeFantasia'];*/
	}

	public function __construct(){
    	parent::__construct();
    	$this->id_usuario	  =null;
    	$this->ds_nome	      =null;
    	$this->ds_senha       =null;
    	$this->ds_mail        =null;
    	$this->id_fisica      =null;
    	$this->id_grupo_acesso=null;
    	$this->dt_cadastro    =null;
    	$this->in_ativo		  =null;
	}

	public function isActive(){
		$ret=false;
		if ($this->id_usuario!=null && $this->in_ativo==1){
			$ret=true;
		}
		return $ret;
	}

    public function salvar(){
    	if ($this->ds_senha==null){
    		$this->passDecrypted = $this->makePassword();
    		$this->ds_senha=md5($this->passDecrypted);
    	}
    	$dados = array('id_usuario'	=>$this->id_usuario,
				 	   'ds_nome'	=>$this->ds_nome,
					   'ds_senha'	=>$this->ds_senha,
					   'ds_mail'	=>$this->ds_mail,
    				   'id_fisica'	=>$this->id_fisica,
				   	   'dt_cadastro'=>$this->dt_cadastro,
    				   'in_ativo'	=>$this->in_ativo,
    	               'id_grupo_acesso' =>$this->id_grupo_acesso);
    	if ($this->id_usuario == null){
			$this->insert($dados);
    	}
    	else {
    		$where = "id_usuario = " . $this->id_usuario;
			$this->update($dados, $where);
    	}
    }

    public function getPass(){
    	return $this->passDecrypted;
    }

    public function setPass(){
    	$this->ds_senha=null;
    }

	public function getId_PessoaJuridica(){
		return $this->id_pessoaJuridica;
	}

	public function getNomeFantasia(){
		return $this->nomeFantasia;
	}

	public function existsUserEmail($user, $email){
		$ret = false;
		if ($user!=null || $email!=null){
			$this->_load($user, $email);
			if ($this->id_usuario!=null){
				$ret = true;
			}
		}
		return $ret;
	}

	public function buscar($usuario=null, $email=null, $order=1, $asc=0){
		$db = Zend_Registry::get('db');
		$sql= 'select *
		         from usuario
		        where 1=1';
		if ($usuario!=null){
			$sql .= ' and ds_nome="'.$usuario.'"';
		}
		if ($email!=null){
			$sql .= ' and ds_mail="'.$email.'"';
		}
		$orderBy = "asc";
		if($asc == 1){
			$orderBy = "desc";
		}
		$sql .= " order by " . $order . " ".$orderBy;

		return $db->query($sql)->fetchAll();
	}

	static function makePassword($pass_len = 6, $pass_num = true, $pass_alpha = true, $pass_mc = true, $pass_exclude = ''){
	    $salt = '';
	    if ($pass_alpha) { // a-z
	        $salt .= 'abcdefghijklmnopqrstuvwxyz';
	        if ($pass_mc) { // A-Z
	            $salt .= strtoupper($salt);
	        }
	    }

	    if ($pass_num) { // 0-9
	        $salt .= '0123456789';
	    }

	    // Remove any excluded chars from salt
	    if ($pass_exclude) {
	        $exclude = array_unique(preg_split('//', $pass_exclude));
	        $salt = str_replace($exclude, '', $salt);
	    }
	    $salt_len = strlen($salt);

	    // Seed the random number generator with today's seed & password's unique settings for extra randomness
	    mt_srand ((int) date('s')*($salt_len+$pass_len));

	    // Generate random password
	    $pass = '';
	    for ($i=0; $i<$pass_len; $i++) {
	        $pass .= substr($salt, mt_rand() % $salt_len, 1);
	    }
		return $pass;
	}

    public function gerarLoginAutomatico($nome, $mail, $pessoa, $id_grupo_acesso){
    	$this->ds_nome     =$nome;
    	$this->ds_mail     =$mail;
    	$this->id_fisica   =$pessoa;
    	$this->in_ativo    =1;
    	$this->dt_cadastro =date('Y-m-d H:m:s');
    	$this->id_grupo_acesso =$id_grupo_acesso;
    	$this->salvar();
    }
}